use std::time::Duration;
use lazy_static::lazy_static;
use log::{info, set_logger_racy};
use tokio::io;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio::runtime::Runtime;
use crate::config::ftlog_init;

///实现一个简单的redis_server
async fn redis_server() {
    let listener = TcpListener::bind("127.0.0.1:16379").await.unwrap();
    info!("connected successfully!!!");
    loop {
        let (stream, _) = listener.accept().await.unwrap();
        process_redis_stream(stream).await;
    }
}

async fn process_redis_stream(mut stream: TcpStream) {
    let mut reader = BufReader::new(&mut stream);
    let mut msg = String::new();
    reader.read_line(&mut msg).await.unwrap();
    info!("{}", msg);
}



/// 模拟Tokio运行时
lazy_static! {
    pub static ref TOKIO_RUNTIME: Runtime = Runtime::new().unwrap();
    static ref ROOT_APP_CONFIG: crate::config::RootAppConfig =
        crate::config::RootAppConfig::new("src/app.yml");
}

#[test]
fn min_redis_server_test() {
    ftlog_init(&ROOT_APP_CONFIG).unwrap();
    TOKIO_RUNTIME.block_on(redis_server());
}

async fn redis_client() {
    let mut stream = TcpStream::connect("127.0.0.1:16379").await.unwrap();
    loop {
        // tokio::time::sleep(Duration::from_secs(2)).await;
        stream.write("this is a msg from client\n".as_bytes()).await.unwrap();// 这里存在问题

        // let mut reader = BufReader::new(&stream);
        let mut buffer = vec![];
        stream.read(&mut buffer).await.unwrap();
        // BufReader::read_until(&mut reader, b'\n', &mut buffer).unwrap();
        info!("read from server :{}",String::from_utf8(buffer).unwrap());

    }
}

#[test]
fn min_redis_client_test() {
    ftlog_init(&ROOT_APP_CONFIG).unwrap();
    TOKIO_RUNTIME.block_on(redis_client());
}